<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>编辑会议 - 测盟汇系统</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios@1.6.7/dist/axios.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
        :root {
            --primary-color: #2c5545;
            --primary-light: #3a7d62;
            --primary-hover: #1e4636;
            --accent-color: #8ba888;
            --error-color: #d64541;
            --success-color: #3a7d62;
            --warning-color: #fdcb6e;
            --info-color: #0984e3;
            --text-color: #333;
            --text-light: #555;
            --border-color: #d1d9d6;
            --bg-light: #f5f7f6;
            --bg-page: #e8ecea;
            --white: #fff;
            --shadow: 0 4px 24px rgba(44, 85, 69, 0.1);
            --radius: 12px;
            --transition: all 0.3s ease;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            color: var(--text-color);
            line-height: 1.6;
            background-color: var(--bg-page);
            min-height: 100vh;
            display: flex;
            align-items: center;
            padding: 1.5rem;
        }

        .container-wrapper {
            max-width: 800px;
            width: 100%;
            margin: 0 auto;
        }

        .edit-container {
            background-color: var(--white);
            border-radius: var(--radius);
            box-shadow: var(--shadow);
            overflow: hidden;
            position: relative;
        }

        .edit-container::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 8px;
            background: linear-gradient(90deg, var(--primary-color), var(--primary-light));
        }

        .page-header {
            padding: 1.5rem 2rem;
            background-color: rgba(44, 85, 69, 0.03);
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid var(--border-color);
        }

        .page-header h2 {
            color: var(--primary-color);
            font-weight: 700;
            font-size: 1.8rem;
            display: flex;
            align-items: center;
            gap: 12px;
            margin: 0;
        }

        .page-header h2 i {
            font-size: 1.5rem;
        }

        .action-buttons {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        .btn {
            border-radius: 6px;
            font-weight: 500;
            padding: 0.65rem 1.25rem;
            transition: var(--transition);
            display: inline-flex;
            align-items: center;
            gap: 8px;
            border: none;
        }

        .btn i {
            font-size: 0.9em;
        }

        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background-color: #5a6268;
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(108, 117, 125, 0.2);
        }

        .btn-success {
            background-color: var(--success-color);
            color: white;
        }

        .btn-success:hover {
            background-color: #2d6b4d;
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(58, 125, 98, 0.2);
        }

        .meeting-id {
            padding: 0.75rem 1.25rem;
            background-color: rgba(44, 85, 69, 0.05);
            border-left: 4px solid var(--primary-color);
            font-weight: 500;
            margin: 1rem 2rem;
            border-radius: 0 var(--radius) var(--radius) 0;
        }

        .form-content {
            padding: 2rem;
        }

        .form-group {
            margin-bottom: 1.75rem;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            margin-bottom: 0.75rem;
            color: var(--primary-color);
            font-size: 1rem;
        }

        .form-control {
            width: 100%;
            padding: 0.85rem 1.25rem;
            border-radius: var(--radius);
            border: 1px solid var(--border-color);
            font-size: 1rem;
            transition: var(--transition);
            background-color: var(--white);
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(44, 85, 69, 0.15);
            outline: none;
        }

        .input-icon {
            position: relative;
        }

        .input-icon i {
            position: absolute;
            right: 18px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--primary-light);
            pointer-events: none;
        }

        .form-control:focus + i {
            color: var(--primary-color);
        }

        textarea.form-control {
            min-height: 120px;
            resize: vertical;
        }

        .custom-file {
            position: relative;
            display: block;
        }

        .custom-file-input {
            position: absolute;
            left: -9999px;
            opacity: 0;
        }

        .custom-file-label {
            display: block;
            padding: 0.85rem 1.25rem;
            border-radius: var(--radius);
            border: 1px solid var(--border-color);
            background-color: var(--white);
            font-size: 1rem;
            cursor: pointer;
            transition: var(--transition);
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            position: relative;
            padding-right: 3rem;
        }

        .custom-file-label::after {
            content: "浏览";
            position: absolute;
            right: 0;
            top: 0;
            bottom: 0;
            background-color: var(--primary-light);
            color: white;
            padding: 0.85rem 1.25rem;
            border-radius: 0 var(--radius) var(--radius) 0;
            font-weight: 500;
        }

        .custom-file-input:focus ~ .custom-file-label {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(44, 85, 69, 0.15);
        }

        .image-preview-container {
            margin-top: 1.5rem;
            border-radius: var(--radius);
            overflow: hidden;
            border: 1px solid var(--border-color);
            max-width: 300px;
            display: none;
        }

        .preview-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            display: block;
        }

        .image-preview-container.active {
            display: block;
            animation: fadeIn 0.4s ease;
        }

        .preview-label {
            display: block;
            text-align: center;
            padding: 0.5rem;
            background-color: var(--bg-light);
            color: var(--text-light);
            font-size: 0.9rem;
        }

        .submit-section {
            margin-top: 2.5rem;
            text-align: center;
        }

        .btn-submit {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
            border: none;
            border-radius: 6px;
            padding: 0.9rem 2.5rem;
            font-weight: 600;
            font-size: 1.1rem;
            transition: var(--transition);
            color: white;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 4px 15px rgba(44, 85, 69, 0.2);
        }

        .btn-submit:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(44, 85, 69, 0.3);
            background: linear-gradient(135deg, var(--primary-hover), var(--primary-color));
        }

        .alert-danger {
            border-radius: var(--radius);
            padding: 1.25rem;
            margin-top: 1.5rem;
            background-color: rgba(214, 69, 65, 0.08);
            color: var(--error-color);
            border-left: 4px solid var(--error-color);
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .form-footer {
            text-align: center;
            padding: 1.5rem;
            color: var(--text-light);
            font-size: 0.9rem;
            border-top: 1px solid var(--border-color);
            margin-top: 1rem;
        }

        .debug-panel {
            background-color: #f8f9fa;
            border-radius: var(--radius);
            padding: 1.25rem;
            margin-top: 1.5rem;
            border: 1px solid #dee2e6;
            display: none;
        }

        .debug-panel.active {
            display: block;
        }

        .debug-toggle {
            background-color: #e9ecef;
            border: none;
            border-radius: 4px;
            padding: 0.5rem 1rem;
            font-size: 0.85rem;
            cursor: pointer;
            margin-top: 1rem;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .debug-toggle:hover {
            background-color: #dee2e6;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @media (max-width: 768px) {
            body {
                padding: 1rem;
            }

            .page-header {
                flex-direction: column;
                gap: 15px;
                align-items: flex-start;
                padding: 1.25rem;
            }

            .action-buttons {
                width: 100%;
                justify-content: flex-start;
            }

            .form-content {
                padding: 1.5rem;
            }

            .image-preview-container {
                max-width: 100%;
            }
        }
    </style>
</head>
<body>
<div class="container-wrapper">
    <div id="app" class="edit-container">
        <div class="page-header">
            <h2>
                <i class="fas fa-calendar-edit"></i>
                编辑会议信息
                <span class="badge" style="background: var(--primary-light); color: white; padding: 0.25rem 0.8rem; border-radius: 50px;">
                    <i class="fas fa-exclamation-circle mr-1"></i>编辑模式
                </span>
            </h2>
            <div class="action-buttons">
                <a th:href="@{/admin/meeting/list}" class="btn btn-secondary">
                    <i class="fas fa-arrow-left mr-1"></i> 返回列表
                </a>
            </div>
        </div>

        <!-- 会议ID展示 -->
        <div class="meeting-id" v-if="meeting.id">
            <i class="fas fa-id-card mr-1"></i>会议ID: <span th:text="${meeting.id}"></span>
        </div>

        <div class="form-content">
            <form id="editForm" th:action="@{/admin/meeting/edit}" method="post" enctype="multipart/form-data" @submit.prevent="checkForm">
                <!-- 添加CSRF token（如果使用Spring Security） -->
                <input type="hidden" name="_csrf" th:value="${_csrf.token}" th:if="${_csrf}">

                <input type="hidden" name="id" th:value="${meeting.id}" v-model="meeting.id">
                <input type="hidden" name="coverImage" :value="meeting.coverImage">

                <div class="form-group input-icon">
                    <label for="title">会议名称</label>
                    <input type="text" class="form-control" id="title"
                           name="title"
                           th:value="${meeting.title}"
                           v-model="meeting.title"
                           required>
                    <i class="fas fa-heading"></i>
                </div>

                <div class="form-group input-icon">
                    <label for="startTime">开始时间</label>
                    <input type="datetime-local" class="form-control" id="startTime"
                           name="startTime"
                           th:value="${#dates.format(meeting.startTime, 'yyyy-MM-dd''T''HH:mm')}"
                           v-model="meeting.startTime"
                           required>
                </div>

                <div class="form-group input-icon">
                    <label for="endTime">结束时间</label>
                    <input type="datetime-local" class="form-control" id="endTime"
                           name="endTime"
                           th:value="${#dates.format(meeting.endTime, 'yyyy-MM-dd''T''HH:mm')}"
                           v-model="meeting.endTime"
                           required>
                </div>

                <div class="form-group input-icon">
                    <label for="creator">创建人</label>
                    <input type="text" class="form-control" id="creator"
                           name="creator"
                           th:value="${meeting.creator}"
                           v-model="meeting.creator"
                           required>
                    <i class="fas fa-user"></i>
                </div>

                <div class="form-group input-icon">
                    <label for="content">会议内容</label>
                    <textarea class="form-control" id="content" name="content" rows="4" required
                              v-model="meeting.content">[[${meeting.content}]]</textarea>
                    <i class="fas fa-file-alt"></i>
                </div>

                <div class="form-group">
                    <label for="coverImage">会议封面图片</label>
                    <div class="custom-file">
                        <input type="file" class="custom-file-input" id="coverImage" name="file"
                               accept="image/*" @change="handleFileUpload">
                        <label class="custom-file-label" for="coverImage" id="fileLabel">{{fileLabelText}}</label>
                    </div>

                    <!-- 图片预览区域 -->
                    <div :class="['image-preview-container', previewImage ? 'active' : '']">
                        <img :src="previewImage" alt="封面预览" class="preview-image">
                        <span class="preview-label">封面预览</span>
                    </div>

                    <!-- 显示当前封面 -->
                    <div v-if="meeting.coverImage && !previewImage" class="current-cover mt-3">
                        <p class="mb-1"><strong>当前封面：</strong></p>
                        <img :src="meeting.coverImage" alt="当前封面" style="max-width: 200px; border-radius: var(--radius);">
                    </div>
                </div>

                <div class="submit-section">
                    <button type="submit" class="btn btn-submit">
                        <i class="fas fa-save"></i> 保存会议
                    </button>
                </div>

                <div v-if="error" class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    <span>{{error}}</span>
                </div>

                <!-- 调试面板 -->
                <div class="debug-panel" :class="{active: showDebug}">
                    <h5><i class="fas fa-bug mr-2"></i>调试信息</h5>
                    <pre>{{ debugInfo }}</pre>
                </div>

                <button type="button" class="debug-toggle" @click="toggleDebug">
                    <i class="fas fa-code"></i> {{ showDebug ? '隐藏调试信息' : '显示调试信息' }}
                </button>
            </form>
        </div>

        <div class="form-footer">
            <p>© 2025 测盟汇系统 | 会议管理模块</p>
        </div>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            meeting: {
                id: [[${meeting.id}]],
                title: "[[${meeting.title}]]",
                startTime: "[[${#dates.format(meeting.startTime, 'yyyy-MM-dd''T''HH:mm')}]]",
                endTime: "[[${#dates.format(meeting.endTime, 'yyyy-MM-dd''T''HH:mm')}]]",
                creator: "[[${meeting.creator}]]",
                content: "[[${meeting.content}]]",
                coverImage: "[[${meeting.coverImage}]]"
            },
            file: null,
            previewImage: '',
            fileLabelText: '选择图片文件 (JPG, PNG)',
            error: '',
            isUploading: false,
            showDebug: false,
            debugInfo: ''
        },
        methods: {
            formatDateTime(dateString) {
                if (!dateString) return '';
                const date = new Date(dateString);
                if (isNaN(date.getTime())) return dateString;
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                return `${year}-${month}-${day}T${hours}:${minutes}`;
            },
            fixDateTime(dateStr) {
                if (!dateStr) return '';
                return dateStr.replace(' ', 'T');
            },
            checkForm() {
                this.error = '';
                document.querySelectorAll('.form-control').forEach(el => {
                    el.classList.remove('is-invalid');
                });

                // 验证必填字段
                const requiredFields = [
                    {id: 'title', name: '会议名称'},
                    {id: 'startTime', name: '开始时间'},
                    {id: 'endTime', name: '结束时间'},
                    {id: 'creator', name: '创建人'},
                    {id: 'content', name: '会议内容'}
                ];

                for (const field of requiredFields) {
                    if (!this.meeting[field.id]) {
                        this.error = `${field.name}不能为空`;
                        this.focusOnError(field.id);
                        return;
                    }
                }

                // 校验时间逻辑
                if (this.meeting.startTime && this.meeting.endTime) {
                    const start = new Date(this.meeting.startTime);
                    const end = new Date(this.meeting.endTime);

                    if (start >= end) {
                        this.error = '结束时间必须晚于开始时间';
                        this.focusOnError('endTime');
                        return;
                    }
                }

                // 准备调试信息
                this.prepareDebugInfo();

                // 如果有文件，先上传文件
                if (this.file) {
                    this.uploadImage();
                } else {
                    this.submitForm();
                }
            },
            focusOnError(fieldId) {
                const input = document.getElementById(fieldId);
                if (input) {
                    input.focus();
                    input.classList.add('is-invalid');
                }
            },
            handleFileUpload(e) {
                const file = e.target.files[0];
                if (file) {
                    this.file = file;
                    this.fileLabelText = file.name;
                    this.previewImage = URL.createObjectURL(file);
                    const isValid = this.validateFile(file);
                    if (!isValid) {
                        this.file = null;
                        this.previewImage = '';
                        this.fileLabelText = '选择图片文件 (JPG, PNG)';
                        e.target.value = '';
                    }
                }
            },
            validateFile(file) {
                const fileType = file.type;
                const fileSize = file.size / 1024 / 1024;

                if (!fileType.match('image.*')) {
                    this.error = '请上传图片文件（支持JPG、PNG等格式）';
                    return false;
                }

                if (fileSize > 5) {
                    this.error = '图片大小不能超过5MB';
                    return false;
                }

                return true;
            },
            uploadImage() {
                this.isUploading = true;
                const formData = new FormData();
                formData.append('file', this.file);

                axios.post('/api/upload/image', formData, {
                    headers: {'Content-Type': 'multipart/form-data'}
                })
                    .then(res => {
                        if (res.data && res.data.url) {
                            this.meeting.coverImage = res.data.url;
                            this.submitForm();
                        } else {
                            this.error = '上传失败：未返回图片URL';
                        }
                    })
                    .catch(err => {
                        let errorMsg = '图片上传失败：';
                        if (err.response) {
                            if (err.response.data) {
                                errorMsg += JSON.stringify(err.response.data);
                            } else {
                                errorMsg += `状态码: ${err.response.status}`;
                            }
                        } else {
                            errorMsg += err.message;
                        }
                        this.error = errorMsg;
                    })
                    .finally(() => {
                        this.isUploading = false;
                    });
            },
            submitForm() {
                // 使用原生表单提交方式
                const form = document.getElementById('editForm');
                const formData = new FormData(form);

                // 添加额外的字段
                formData.append('coverImage', this.meeting.coverImage);

                // 添加调试信息
                this.debugInfo += '\n\n提交的表单数据:';
                for (let [key, value] of formData.entries()) {
                    this.debugInfo += `\n${key}: ${value}`;
                }

                // 使用原生表单提交
                form.submit();
            },
            prepareDebugInfo() {
                this.debugInfo = `会议数据:\n${JSON.stringify(this.meeting, null, 2)}`;

                if (this.file) {
                    this.debugInfo += `\n\n文件信息:\n名称: ${this.file.name}\n类型: ${this.file.type}\n大小: ${(this.file.size / 1024).toFixed(2)} KB`;
                }
            },
            toggleDebug() {
                this.showDebug = !this.showDebug;
                if (this.showDebug) {
                    this.prepareDebugInfo();
                }
            }
        },
        mounted() {
            // 修复时间格式
            this.meeting.startTime = this.fixDateTime(this.meeting.startTime);
            this.meeting.endTime = this.fixDateTime(this.meeting.endTime);

            // 设置当前封面图片预览
            if (this.meeting.coverImage) {
                this.previewImage = this.meeting.coverImage;
            }
        }
    });
</script>
</body>
</html>